﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Kugar.Core.BaseStruct;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Kugar.Tool.DataSync.ServerPlugin
{
    /// <summary>
    /// 默认的Http传输器,用于对接默认的客户端接收器
    /// </summary>
    public class DefaultHttpTransfer
    {
        private string _host = "";

        public DefaultHttpTransfer(string host)
        {
            _host = host;

            if (!_host.StartsWith("http://",StringComparison.CurrentCultureIgnoreCase))
            {
                _host = "http://" + _host;
            }
        }

        public ResultReturn SendData( string appID, string dataTypeName, JObject data)
        {
            using (var client = new WebClient())
            {
                client.BaseAddress = _host;

                try
                {
                    var u =
                        $"{_host}/Import/{appID}/{WebUtility.UrlEncode(dataTypeName)}";

                    var ret = client.UploadString(u, "POST", data.ToString(Formatting.None));

                    return JsonConvert.DeserializeObject<ResultReturn>(ret);
                }
                catch (Exception ex)
                {
                    return new FailResultReturn(ex);
                }
            }
        }
    }
}
